package com.dd.cloud.user.service.search.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.SearchConstants;
import com.dd.cloud.user.entity.search.SearchHot;
import com.dd.cloud.user.mapper.search.SearchHotMapper;
import com.dd.cloud.user.service.search.ISearchHotService;
import com.dd.cloud.user.vo.HjtResponseVo;
import com.dd.cloud.common.utils.JsonUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 热门搜索表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-07-05
 */
@Service
public class SearchHotServiceImpl extends ServiceImpl<SearchHotMapper, SearchHot> implements ISearchHotService {

    /**
     * 保存热门搜索次数
     *
     * @param modular   搜索的模块
     * @param submodule 搜索的子模块
     */
    @Override
    public void saveSearchHot(String modular, String submodule, String search) {
        QueryWrapper<SearchHot> qw = new QueryWrapper<>();
        qw.lambda().eq(SearchHot::getSearch, search)
                .eq(SearchHot::getModular, modular)
                .eq(SearchHot::getSubmodule, submodule)
                .eq(SearchHot::getStatus, SearchConstants.SearchStatus.NOMER);
        SearchHot searchHot = getOne(qw);
        if (searchHot == null) {
            searchHot = new SearchHot();
            searchHot.setSearch(search);
            searchHot.setModular(modular);
            searchHot.setSubmodule(submodule);
            searchHot.setStatus(SearchConstants.SearchStatus.NOMER);
            searchHot.setCreateDate(LocalDateTime.now());
            searchHot.setNum(1);
            save(searchHot);
            return;
        }
        searchHot.setNum(searchHot.getNum() + 1);
        updateById(searchHot);
    }

    /**
     * 查询热门搜索列表
     *
     * @return
     */
    @Override
    public List<SearchHot> getSearchHotList() {
        QueryWrapper<SearchHot> qw = new QueryWrapper<>();
        qw.lambda().eq(SearchHot::getModular, SearchConstants.Modular.CHSCIENCE)
                .eq(SearchHot::getStatus, SearchConstants.SearchStatus.NOMER)
                .orderByDesc(SearchHot::getNum);
        Page<SearchHot> page = new Page(1, 12);
        page = getBaseMapper().selectPage(page, qw);
        return page.getRecords();
    }

    public static void main(String[] args) {
        String json = "\"{\"dhy_error_code\":\"47001\",\"dhy_error_msg\":\"不是完整接口信息，请添贴数字段!\"}\"";
        if (json.startsWith("\"")){
            json = json.substring(1, json.length());
        }
        if (json.endsWith("\"")){
            json = json.substring(0, json.length()-1);
        }
        HjtResponseVo vo = JsonUtils.parse(json, HjtResponseVo.class);
        System.out.println(vo);
    }
}
